import { mergeCart, findCartList, insertCart, deleteCart, updateCart, checkAllCart } from '@/api/cart.js'
// 购物车状态
export default {
  namespaced: true,
  state: () => {
    return {
      list: []
    }
  },
  getters: {
    // 有效商品列表
    effectiveList (state) {
      return state.list.filter(item => item.stock > 0 && item.isEffective)
    },
    // 有效商品总件数
    // 一个getter中去取另一个getters
    allCount (state, getters) {
      return getters.effectiveList.reduce((p, c) => p + c.count, 0)
    },
    // 有效商品总金额
    allAmount (state, getters) {
      return getters.effectiveList.reduce((p, c) => p + c.nowPrice * c.count, 0)
    },
    // 无效商品列表
    invalidList (state) {
      return state.list.filter(item => !(item.stock > 0 && item.isEffective))
    },
    // 选中商品列表
    selectedList (state, getters) {
      return getters.effectiveList.filter(item => item.selected)
    },
    // 选中商品件数
    selectedTotal (state, getters) {
      return getters.selectedList.reduce((p, c) => p + c.count, 0)
    },
    // 选中商品总金额
    selectedAmount (state, getters) {
      return getters.selectedList.reduce((p, c) => p + (c.nowPrice * c.count), 0)
    },
    // 是否全选
    isCheckAll (state, getters) {
      return getters.effectiveList.length === getters.selectedList.length && getters.selectedList.length !== 0
    }
  },
  mutations: {
    // 添加商品
    insertCart (state, payload) {
      const goods = state.list.find(it => it.skuId === payload.skuId)
      if (goods) {
        goods.count += payload.count
      } else {
        state.list.push(payload)
      }
    },
    // 删除商品
    deleteCart (state, skuId) {
      const idx = state.list.findIndex(it => it.skuId === skuId)
      state.list.splice(idx, 1)
    },
    // 更新购物车（修改）count,selected
    updateCart (state, goods) {
      // 找到传进来的skuid找到与之对应的元素
      const obj = state.list.find(it => it.skuId === goods.skuId)
      if (obj) {
        for (const p in obj) {
          // 循环查找并更新
          if (goods[p] !== undefined && goods[p] !== null) {
            obj[p] = goods[p]
          }
        }
      }
    },
    // 修改sku
    updateCartSku (state, { newSku, oldSkuId }) {
      const oldSkuIdx = state.list.findIndex(it => it.skuId === oldSkuId)
      if (oldSkuIdx === -1) { return }
      // 旧的sku复制一份
      const oldSkuCopy = { ...state.list[oldSkuIdx] }
      // // specsText
      const { skuId, price: nowPrice, oldPrice: price, inventory: stock, specsText: attrsText } = newSku._rawValue
      // 覆盖获得新的sku数据
      const newGoods = { ...oldSkuCopy, skuId, nowPrice, stock, attrsText, price }

      // // 删除旧的加入新的
      state.list.splice(oldSkuIdx, 1, newGoods)
    },
    // 统一设置购物车
    setCartList (state, list) {
      // 同步到本地购物车数据
      state.list = list
    }
  },
  actions: {
    insertCart (ctx, payload) {
      return new Promise((resolve, reject) => {
        // 判断是否登录
        if (ctx.rootState.user.profile.token) {
          insertCart(payload).then(() => {
            return findCartList() // 获取新的购物车数据
          }).then((data) => {
            ctx.commit('setCartList', data.result)
            resolve()
          })
        } else { // 未登录
          ctx.commit('insertCart', payload)
          resolve()
        }
      })
    },
    // 删除购物车商品
    deleteCart (ctx, skuId) {
      return new Promise((resolve, reject) => {
        if (ctx.rootState.user.profile.token) {
          // 登录
          deleteCart([skuId]).then(() => {
            return findCartList()
          }).then((data) => {
            ctx.commit('setCartList', data.result)
            resolve()
          })
        } else {
          // 本地
          ctx.commit('deleteCart', skuId)
          resolve()
        }
      })
    },
    // 批量删除选中的商品 & 批量删除无效的商品
    batchDeleteCart (ctx, isClearInvalidCart) {
      return new Promise((resolve, reject) => {
        if (ctx.rootState.user.profile.token) {
          const skuId = ctx.getters[isClearInvalidCart ? 'invalidList' : 'selectedList'].map(it => it.skuId)
          // 登录
          deleteCart(skuId).then(() => {
            return findCartList()
          }).then((data) => {
            ctx.commit('setCartList', data.result)
            resolve()
          })
        } else {
          // 本地
          // 批量删除选中的商品 & 批量删除无效的商品
          ctx.getters[isClearInvalidCart ? 'invalidList' : 'selectedList'].forEach(it => {
            ctx.commit('deleteCart', it.skuId)
          })
          resolve()
        }
      })
    },
    // 修改购物车商品
    updateCart (ctx, goods) {
      return new Promise((resolve, reject) => {
        if (ctx.rootState.user.profile.token) {
          // 登录 updateCart
          updateCart(goods).then(() => {
            return findCartList() // 获取新的购物车数据
          }).then((data) => {
            ctx.commit('setCartList', data.result)
            resolve()
          })
        } else {
          // 本地
          ctx.commit('updateCart', goods)
          resolve()
        }
      })
    },
    // 批量选中购物车商品
    checkAllCart (ctx, selected) {
      return new Promise((resolve, reject) => {
        if (ctx.rootState.user.profile.token) {
          // 登录 checkAllCart
          const ids = ctx.getters.effectiveList.map(it => it.skuId)
          checkAllCart({ selected, ids }).then(() => {
            return findCartList() // 获取新的购物车数据
          }).then((data) => {
            ctx.commit('setCartList', data.result)
            resolve()
          })
        } else {
          // 本地
          // 对有效的商品列表数据循环调用mutations，更新选中的商品
          ctx.getters.effectiveList.forEach(it => {
            ctx.commit('updateCart', { skuId: it.skuId, selected })
          })
          resolve()
        }
      })
    },
    // 修改sku
    updateCartSku (ctx, { newSku, oldSkuId }) {
      return new Promise((resolve, reject) => {
        if (ctx.rootState.user.profile.token) {
          // 登录updateCartSku
          // 1. 获取原先商品的数量
          // 2. 删除原先商品
          // 3. 获取修改的skuId 和 原先商品数量 做一个加入购物车操作
          // 4. 更新列表
          const oldGoods = ctx.state.list.find(item => item.skuId === oldSkuId)
          const count = oldGoods.count // 获取数据
          deleteCart([oldSkuId]).then(() => {
            insertCart({ skuId: newSku._rawValue.skuId, count }).then(() => {
              // 3. 获取最新的购物车
              findCartList().then(data => {
                ctx.commit('setCartList', data.result)
                resolve()
              })
            })
          })
        } else {
          // 本地
          ctx.commit('updateCartSku', { newSku, oldSkuId })
          resolve()
        }
      })
    },
    // 登录成功后：合并购物车（本地上传-->自动合并）；
    // 获取最新的购物车数据（同步到本地）
    async mergeLocalCart (ctx) {
      const list = ctx.state.list.map(it => {
        return {
          skuId: it.skuId,
          count: it.count,
          selected: it.selected
        }
      })
      try {
        await mergeCart(list)
        // 获取最新的购物车数据
        const data = await findCartList()
        ctx.commit('setCartList', data.result)
      } catch (err) {
        throw new Error(err.response.data.message)
      }
    }
  }
}
